//转换Date to yyyy/MM/dd HH24miss
function formatTime(date) {
  if (undefined == date || date == 'undefined' || date == '')
    return '';
  var newDate = new Date();
  newDate.setTime(date);
  var year = newDate.getFullYear();
  var month = newDate.getMonth() + 1;
  var day = newDate.getDate();

  var hour = newDate.getHours();
  var minute = newDate.getMinutes();
  var second = newDate.getSeconds();

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}

// 转换时间显示格式  20140601 --> 2014-06-01
function formatDateYYYYmmdd(originDate, seperator) {
  var result = ''

  var tSeperator = '-'
  if (seperator != null && seperator != '') {
    tSeperator = seperator
  }

  originDate = originDate + ''
  var length = originDate.length
  if (length >= 8) {
    var year = originDate.substr(0, 4)
    var month = originDate.substr(4, 2)
    var day = originDate.substr(6, 2)
    result = year + tSeperator + month + tSeperator + day
  }

  return result
}

// 1507111022 15年07月11日11时22分 -> 15/07/11/10:22
function formatDateY_M_D_HHmm(orgDate, separator) {
  var fixDate = '';
  var t_separator = '/';
  if (separator != null && separator != '') {
    t_separator = separator;
  }

  var nlen = orgDate.length;
  if (nlen >= 10) {
    var tYear = orgDate.substring(0, 2);
    var tMonth = orgDate.substring(2, 4);
    // if (tMonth.substr(0, 1) == '0') {
    //     tMonth = tMonth.substr(1, 1);
    // }

    var tDay = orgDate.substring(4, 6);
    // if (tDay.startsWith("0")) {
    //     tDay = tDay.replace("0", "");
    // }

    var tHour = orgDate.substring(6, 8);

    var tMinute = orgDate.substring(8, 10);

    fixDate = tYear + t_separator + tMonth + t_separator + tDay + t_separator + tHour + ":" + tMinute;
  }
  return fixDate;
}

//转换Date(TimeStamp) to yyyy/MM/dd
function formatDate(date) {
  if (undefined==date||date=='undefined'||date=='')
    return '';
  var newDate = new Date();
  newDate.setTime(date);
  var year = newDate.getFullYear();
  var month = newDate.getMonth() + 1;
  var day = newDate.getDate();
  return [year, month, day].map(formatNumber).join('/');
}

//转换second to HH24:mi
function formatSqlTime(date) {
  if (undefined==date||date=='undefined'||date=='')
    return '';
  var hour = Math.floor((date) / (3600*1000));
  var minute = Math.floor((date - hour * 3600 * 1000) / (60*1000));
  return [hour + 8, minute].map(formatNumber).join(':');
}


//转化时间戳
function formatTimeStamp(date){
  if (undefined==date||date=='undefined'||date=='')
    return '';
  var newDate = new Date();
  newDate.setTime(date);
  return formatTime(newDate);
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//隐藏手机信息
function hidePrivacy(mobile){
  if (mobile.length < 11) {
    return mobile;
  }
  return mobile.substr(0, 3) + '****' + mobile.substr(7);  
}


//发送手机验证码组件，引用页面data-->verifyCode,authButton
function auth_mobile(that,mobile){
  var total_micro_second = 60 * 1000;
  count_down(that, total_micro_second);

  wx.request({
    data: { mobile: mobile},
    header: getApp().globalData.header,
    url: getApp().globalData.host + '/captcha/sendSmsCaptcha.html',
    success: function success(res) {
      var resultMsg = '验证码已发送';
      if (0 != res.data.errorCode) {
        resultMsg = '验证码发送失败';
      }
      wx.showToast({
        title: resultMsg
      });
    }
  });
}

/* 毫秒级倒计时 */
function count_down(that, total_micro_second) {
  if (total_micro_second <= 0) {
    that.setData({
      verifyCode: "重新发送"
    });
    that.setData({
      authButton: false
    })
    // timeout则跳出递归
    return;
  }
  that.setData({
    authButton: true
  })
  // 渲染倒计时时钟
  that.setData({
    verifyCode: date_format(total_micro_second) + " 秒"
  });
  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 100;
    count_down(that, total_micro_second);
  }, 100)
}
// 时间格式化输出，如03:25:19 86。每100ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));
  return sec;
}
// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}

function uuid() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  //s[8] = s[13] = s[18] = s[23] = "-";  不需要 - 
  return s.join("");
}
function imageUrl(imgurl){
  if(typeof(imgurl)!='undefined'&&imgurl.indexOf('img/')<2){
    imgurl = getApp().globalData.imgHost + imgurl;
  }
  return imgurl;
}

/** 将JSON数组转换为url参数形式 */
function obj2Url(obj){
  let result = "";
  if (typeof (obj) == 'undefined' || obj==null)
    return result;
  for (let i in obj){
    result = result + i + "=" + obj[i] + "&";
  }
  return result;
}

//模拟sleep d 休眠毫秒数
function sleep(d) {
  for (var t = Date.now(); Date.now() - t <= d;);
}

module.exports = {
  formatTime: formatTime,
  auth_mobile: auth_mobile,
  hidePrivacy: hidePrivacy,
  formatTimeStamp:formatTimeStamp,
  formatDate:formatDate,
  formatSqlTime:formatSqlTime,
  formatDateY_M_D_HHmm: formatDateY_M_D_HHmm,
  formatDateYYYYmmdd: formatDateYYYYmmdd,
  uuid:uuid,
  imageUrl:imageUrl,
  obj2Url: obj2Url,
  sleep: sleep
}
